<template>
  <div class="tab-container">
    <div class="flex-between">
      <el-button
        type="primary"
        @click="handleAddUser"
      >新增会员</el-button>
      <div>
        <el-autocomplete
          v-model="search"
          :fetch-suggestions="querySearchAsync"
          placeholder="请输入要查找的手机号"
          value-key="mobile"
          @select="handleSelect"
          @keyup.enter.native="handleSelect2"
        />
        <el-button
          slot="append"
          icon="el-icon-search"
        />
      </div>
    </div>

    <!-- <el-tag>会员总数：10</el-tag> -->
    <el-tabs
      v-model="activeName"
      style="margin-top:15px;"
      type="border-card"
    >
      <el-tab-pane
        v-for="item in tabMapOptions"
        :key="item.key"
        ref="tab"
        :label="item.label"
        :name="item.key"
      >
        <keep-alive>
          <tab-pane
            v-if="activeName==item.key"
            ref="pushData"
            :type="item.key"
            @create="showCreatedTimes"
            @toDetailUser="toDetailUser"
            @editUser="editUser"
          />
        </keep-alive>
      </el-tab-pane>
    </el-tabs>

    <el-dialog
      :visible.sync="dialogVisible"
      :title="dialogType==='edit'?'编辑会员':'新建会员'"
    >
      <el-form
        :model="user"
        label-width="80px"
        label-position="left"
      >
        <el-form-item
          label="手机号"
          required=""
        >
          <el-input
            v-model="user.mobile"
            placeholder="请输入手机号"
          />
        </el-form-item>
        <el-form-item
          label="姓名"
          required=""
        >
          <el-input
            v-model="user.username"
            placeholder="请输入姓名"
          />
        </el-form-item>
        <el-form-item
          label="性别"
          required=""
        >
          <el-radio-group v-model="user.sex">
            <el-radio :label="1">男</el-radio>
            <el-radio :label="2">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          label="会员等级"
          required=""
        >
          <el-select
            v-model="user.level"
            placeholder="请选择"
          >
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          label="出生日期"
          required=""
        >
          <el-date-picker
            v-model="user.birthday"
            type="date"
            value-format="timestamp"
            placeholder="选择日期"
          />
        </el-form-item>
      </el-form>
      <div style="text-align:right;">
        <el-button
          type="danger"
          @click="dialogVisible=false"
        >取消</el-button>
        <el-button
          type="primary"
          @click="confirmRole"
        >确定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import TabPane from './components/TabPane'
import { deepClone } from '@/utils'
import { getUser, addUser, updateUser, getUserMobile } from '@/api/user'
import { sexC } from '@/utils/role'
import { addPrescription } from '@/api/prescription'
import { mapGetters } from 'vuex'
import { getNowFormatDate } from '@/utils/time'

const userDefault = {
  username: '',
  birthday: '',
  sex: '',
  mobile: '',
  level: '1'
}
export default {
  name: 'Tab',
  components: { TabPane },
  data() {
    return {
      tabMapOptions: [
        { label: '所有', key: 'CN' }
      ],
      user: Object.assign({}, userDefault),
      activeName: 'CN',
      createdTimes: 0,
      dialogVisible: false,
      presciptionVisible: false,
      dialogType: 'new',
      search: '',
      radio: '1',
      dialogDepartment: false,
      options: [{
        value: '1',
        label: '1级会员'
      }, {
        value: '2',
        label: '2级会员'
      }, {
        value: '3',
        label: '3级会员'
      }, {
        value: '4',
        label: '4级会员'
      }, {
        value: '5',
        label: '5级会员'
      }]
    }
  },
  computed: {
    ...mapGetters(['adminId'])
  },
  watch: {
    activeName(val) {
      this.$router.push(`${this.$route.path}?tab=${val}`)
    }
  },
  created() {
    // init the default selected tab
    // const tab = this.$route.query.tab
    // if (tab) {
    //   this.activeName = tab
    // }
    // this.getUser()
  },
  methods: {
    async getUser() {
      const res = await getUser()
      console.log(res)
      for (const i in res.data) {
        res.data[i].sexC = sexC(res.data[i].sex)
        res.data[i].key = i
      }
      this.rolesList = res.data
    },
    showCreatedTimes() {
      this.createdTimes = this.createdTimes + 1
    },
    handleAddUser() {
      this.user = Object.assign({}, userDefault)
      this.dialogType = 'new'
      this.dialogVisible = true
    },
    editUser(scope) {
      this.dialogVisible = true
      this.dialogType = 'edit'
      this.user = deepClone(scope.row)
      this.user.level = this.user.level.toString()
      console.log(this.user)
    },
    async toDetailUser(scope) { // 跳转到写病历
      const data = await addPrescription({ userId: scope.row.id, adminId: this.adminId, medicationTimeStart: Date.parse(new Date()),
        medicationTimeEnd: Date.parse(new Date()) })
      this.$router.push({
        name: 'prescriptionDetail',
        params: {
          userId: scope.row.id,
          prescriptionId: data.data
        }
      })
    },
    async confirmRole() {
      const isEdit = this.dialogType === 'edit'
      if (isEdit) {
        console.log(this.user)
        delete this.user.createTime
        await updateUser(this.user)
        const userList = this.$refs.pushData[0].userList
        for (let index = 0; index < userList.length; index++) {
          if (userList[index].key === this.user.key) {
            this.user.createTime = getNowFormatDate(new Date())
            userList.splice(index, 1, Object.assign({}, this.user))
            break
          }
        }
      } else {
        const userdata = Object.assign(this.user)
        // userdata.birthday = userdata.birthday.getTime()
        const { data } = await addUser(userdata)
        this.total++
        this.user.id = data
      }

      this.$refs.pushData[0].getUser({
        pageNum: 1,
        pageSize: 10,
        queryStatic: 1
      })
      const { username } = this.user
      this.dialogVisible = false
      this.$notify({
        title: '成功',
        dangerouslyUseHTMLString: true,
        message: `
            <div>姓名: ${username}</div>
          `,
        type: 'success'
      })
    },
    async querySearchAsync(queryString, cb) {
      var results = []
      if (queryString) {
        const queryData = { mobileLike: queryString, pageSize: 20 }
        const { data } = await getUserMobile(queryData)
        console.log(data)
        if (data.length === 0) {
          results = [{ 'mobile': '暂无数据' }]
          cb(results)
        } else {
          results = data
          cb(results)
        }
      } else {
        cb(results)
      }
    },
    handleSelect(item) {
      this.$refs.pushData[0].getUser(item)
    },
    handleSelect2() {
      this.$refs.pushData[0].getUser({ mobile: this.search })
    }
  }
}
</script>

<style scoped>
.tab-container {
  margin: 30px;
}
</style>
